<?php

namespace backend\controllers;

use backend\models\Basemodule;
use backend\models\Baserole;
use yii;

class RoleController extends CommonController
{
    /**
     * @param \yii\base\Action $action
     * @return bool
     * @throws \yii\web\BadRequestHttpException
     */
    public function beforeAction($action)
    {
        if (parent::beforeAction($action)) {
            if ($this->roleId > 2 && $this->roleId < 10){
                return false;
            }
            return true;
        } else {
            return false;
        }
    }

    public function actionIndex()
    {
        $moduleId = yii::$app->request->get('moduleId');
        $groupId = yii::$app->request->get('groupid');
        $module = Basemodule::findOne(['Id' => $moduleId]);
        if (yii::$app->request->isPost){
            $roleModel = new Baserole();
            $groupList = $roleModel->getRoleList($groupId);
            return $this->renderJson($groupList);
        }
        $citem = Basemodule::getMoreRole($this->roleId, $moduleId);
        $data = [
            'module' => $module,
            'citem' => $citem,
            'groupId' => $groupId,
        ];
        return $this->renderPartial('index',$data);
    }


    public function actionCreate()
    {
        if (yii::$app->request->isPost){
            $post = yii::$app->request->post();
            if (empty($post['RoleId'])){//添加
                $role = new Baserole();
                $result = $role->insertData($post);
            }else{//修改
                $role = Baserole::findOne(['Id' => $post['RoleId']]);
                $result = $role->updateData($post);
            }
            return $this->renderJson($result);
        }else{
            $roleId = yii::$app->request->get('id');
            $groupId = yii::$app->request->get('gid');
            $role = Baserole::findOne(['Id'=>$roleId, 'GroupId'=>$groupId]);
            $data = [
                'role' => $role,
                'roleId' => $roleId,
                'groupId' => $groupId,
            ];
        }
        return $this->renderPartial('create', $data);
    }


    public function actionHandler()
    {
        $data = yii::$app->request->get();
        $role = new Baserole();
        $result = $role->deleteRole($data);
        return $this->renderJson($result);
    }


}
